import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:squat_easy/se_net/se_global_url.dart';
import 'package:squat_easy/se_net/se_net.dart';
import 'package:squat_easy/se_route.dart';
import 'package:squat_easy/se_service/se_log_service.dart';
import 'package:squat_easy/se_service/se_oss_service.dart';
import 'package:squat_easy/se_service/se_user_service.dart';
import 'package:squat_easy/se_ui/se_dialogs.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:ylm_ui_kit/ylm_ui_kit.dart';

class SeApiUpdateInfo extends SeApi {
  SeApiUpdateInfo.updateAvatar(String avatarPath) : super(SeGlobalUrl.updateAvatar, params: {'avatarPath': avatarPath});

  SeApiUpdateInfo.update({String? birthday, String? country, String? nickname})
      : super(
          SeGlobalUrl.updateUserInfo,
          params: {
            if (birthday.notEmpty) 'birthday': birthday,
            if (country.notEmpty) 'country': country,
            if (nickname.notEmpty) 'nickname': nickname,
          },
        );
}

class SeEditInfoLogic extends GetxController with OnceClick {
  final TextEditingController textEditingController = TextEditingController();

  final ValueNotifier<String> birth = ValueNotifier('');
  final ValueNotifier<String> country = ValueNotifier('');
  final ValueNotifier<String> filePath = ValueNotifier('');
  List<String> countryList = [];

  ValueNotifier<bool> enableSubmit = ValueNotifier(false);

  void check() {
    String icon = SeUserService.instance.notifierOfMineInfo.value.avatarThumbUrl ?? '';
    String name = SeUserService.instance.notifierOfMineInfo.value.nickname ?? '';
    String birth = SeUserService.instance.notifierOfMineInfo.value.birthday ?? '';
    String country = SeUserService.instance.notifierOfMineInfo.value.country ?? '';

    enableSubmit.value = (textEditingController.text.notEmpty &&
            this.birth.value.notEmpty &&
            this.country.value.notEmpty &&
            filePath.value.notEmpty) &&
        (!textEditingController.text.equals(name) ||
            !this.birth.value.equals(birth) ||
            !this.country.value.equals(country) ||
            !filePath.value.equals(icon));
  }

  void addListen() {
    textEditingController.addListener(check);
    birth.addListener(check);
    country.addListener(check);
    filePath.addListener(check);
  }

  void removeListen() {
    textEditingController.removeListener(check);
    birth.removeListener(check);
    country.removeListener(check);
    filePath.removeListener(check);
  }

  @override
  void onReady() async {
    super.onReady();
    addListen();
    textEditingController.text = SeUserService.instance.notifierOfMineInfo.value.nickname ?? '';
    birth.value = SeUserService.instance.notifierOfMineInfo.value.birthday ?? '';
    country.value = SeUserService.instance.notifierOfMineInfo.value.country ?? '';
    filePath.value = SeUserService.instance.notifierOfMineInfo.value.avatarThumbUrl ?? '';
    check();
    await _getCountryList();
    update();
  }

  Future _getCountryList() async {
    try {
      String result = await rootBundle.loadString('assets/json/country.json');
      dynamic json = jsonDecode(result);
      if (json is List) {
        countryList = await CommonJson.getList(json, (json) => json['en']);
      }
    } catch (_) {}
  }

  @override
  void onClose() {
    removeListen();
    textEditingController.dispose();
    super.onClose();
  }

  Future changeAvatar() async {
    SeLogManager.stat(page: SeLogPage.editAvatar);

    ActionBottomSheet.actionSheet(items: [
      ActionSheetConfig(
        text: 'Take Photo',
        onTap: () async {
          CommonPrivilegeStatus status = await CommonPrivilege.camera();
          if (!status.result) {
            SeDialogs.twoButton(
              title: status.title,
              description: status.message,
              cancelTitle: YlmGlobalConfig().actionSheetConfig.cancelTitle,
              confirmTitle: YlmGlobalConfig().actionSheetConfig.confirmTitle,
              onConfirm: () => CommonPrivilege.openSettings(),
            );
            return;
          }
          AssetEntity? assetEntity = await ActionPicker.camera(locale: const Locale('en', 'US'));
          if (assetEntity == null) return;
          filePath.value = (await assetEntity.file)?.path ?? '';
          update();
        },
      ),
      ActionSheetConfig(
        text: 'Choose From Library',
        onTap: () async {
          CommonPrivilegeStatus status = await CommonPrivilege.photos();
          if (!status.result) {
            SeDialogs.twoButton(
              title: status.title,
              description: status.message,
              cancelTitle: YlmGlobalConfig().actionSheetConfig.cancelTitle,
              confirmTitle: YlmGlobalConfig().actionSheetConfig.confirmTitle,
              onConfirm: () => CommonPrivilege.openSettings(),
            );
            return;
          }

          List<AssetEntity> list = await ActionPicker.assets() ?? [];
          if (list.isEmpty) return;
          filePath.value = (await list.first.file)?.path ?? '';
          update();
        },
      ),
    ]);
  }

  Future submit() async {
    if (!enableSubmit.value) return;
    startOnce(() async {
      if (filePath.value.notEmpty) await uploadAvatar();
      await SeApiUpdateInfo.update(
        birthday: birth.value,
        country: country.value,
        nickname: textEditingController.text,
      ).post();
      await SeUserService.instance.getCacheMineInfoBean(true);
      Loading.dismiss();
      SeRoute.close();
    }, clickMaskDismiss: false);
  }

  Future uploadAvatar() async {
    SeOssResultBean? bean = await SeOssService.uploadFile(filePath.value);
    String filename = bean?.filename ?? '';
    if (filename.notEmpty) await SeApiUpdateInfo.updateAvatar(filename).post();
    await CommonStorage().setBool(SeUserService.instance.editAvatarKey, true);
  }
}
